package com.tuojiahr.tools;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

import com.tuojiahr.global.Constants;

/**
 * 文件操作
 *
 */
public class FileUtil {
	
	/**
	 * 将一个文件读入到磁盘上的图片(文件copy)
	 * 
	 * @param tempImg	源文件	
	 * @param secDicName	二级目录	
	 * @param imgName	磁盘上的文件名
	 * @return boolean
	 */
	public static boolean fileToImg(File tempImg, String secDicName, String imgName) {
		boolean flag = false;
		File file = new File(FileUtil.class.getResource("/").getPath());
		String truePath = file.getParentFile().getParent();
		if(StringUtil.isNotBlank(secDicName)) {
			truePath += File.separator + "webimg" + File.separator + secDicName + File.separator;
		} else {
			truePath += File.separator + "webimg" + File.separator;
		}
		
		File trueFile = new File(truePath);
		FileOutputStream fos = null;
		FileInputStream fis = null;
		if(!trueFile.exists()) {
			trueFile.mkdirs();
		}
		try {
			//不存在,创建文件
			File imgFile = new File(trueFile, imgName);
			if(!imgFile.exists()) {
				imgFile.createNewFile();
			}
			fos = new FileOutputStream(imgFile);
			fis = new FileInputStream(tempImg);
			int length = fis.available();
			if(length > 0){
		        byte[] buffer = new byte[length];
		        int len = 0;
		        while ((len = fis.read(buffer)) > 0) {
		            fos.write(buffer, 0, len);
		        }
	        }
	        fos.close();
	        fos.flush();
	        fis.close();
	        flag = true;
		}catch (Exception e) {
			Constants.ExceptionLog.error("##Converter类------------fileToImg写入文件出错：", e);
		}
        return flag;
	}
	
}
